package omg.loot;

public class Camera {
   public static final double ZOOM_SPEED = 0.009d;
   public static final float ZOOM_MAX = 3f;
   public static final float ZOOM_MIN = 0.5f;
   public static final float ZOOM_STEP = 0.25f;

   protected MouseReader mouse;

   protected double interestingX = Main.CENTERX, interestingY = Main.CENTERY;
   protected long zoomStop = System.nanoTime();
   protected double zoom = 1d;
   protected double x = 0, y = 0; //Camera position (0,0 = Top-left of the playfield)

   //Temps: (holds the values during drawing)
   protected float t_zoom;
   protected float t_x, t_y;

   public Camera(final MouseReader mouse) {
      this.mouse = mouse;
      saveValues();
   }

   public void saveValues() {
      t_zoom = (float)zoom;
      t_x = (float)x;
      t_y = (float)y;
   }

   public void updateCamera(final double delta) {
      //Update camera's zoom gradually from mouse's level:
      if (Math.abs((mouse.zoom/100d-zoom)*delta*ZOOM_SPEED) < 0.01) { //If the zoom is almost done
         zoom = mouse.zoom/100d; //Just set the level directly
      }
      else { //If we are still zooming
         if (mouse.zoom > zoom*100) { //If we are zooming in, move the camera as well:
            if ((System.nanoTime()-zoomStop)/Shared.divider > 500) { //If we are starting to zoom in
               interestingX = x-mouse.x;
               interestingY = y-mouse.y;
            }
            zoomStop = System.nanoTime();
            x += (interestingX-x+Main.CENTERX*Shared.scaleX)*delta*ZOOM_SPEED;
            y += (interestingY-y+Main.CENTERY*Shared.scaleY)*delta*ZOOM_SPEED;
         }
         zoom += (mouse.zoom/100d-zoom)*delta*ZOOM_SPEED;
      }
      //Move the camera:
      x += mouse.scrollX/zoom;
      y += mouse.scrollY/zoom;
      mouse.scrollX = 0;
      mouse.scrollY = 0;
      //Fling the camera:
      x += mouse.fling_resultX/zoom;
      y += mouse.fling_resultY/zoom;
      mouse.fling_resultX *= 0.8d;
      mouse.fling_resultY *= 0.8d;
      //Calculate the tile index mouse cursor hovers over:
      final double xz = (Main.WIDTH-Main.WIDTH/zoom)*0.5;
      final double yz = (Main.HEIGHT-Main.HEIGHT/zoom)*0.5;
      final int tempX = (int) ((xz+Tile.r+mouse.x/zoom-x)/Tile.size);
      final int tempY = (int) ((yz+Tile.r+mouse.y/zoom-y)/Tile.size);
      //Check if the cursor is on the playfield or not:
      if (tempX < 0 || tempX >= Map.WIDTH || tempY < 0 || tempY >= Map.HEIGHT)
         mouse.isOnPlayfield = false;
      else {
         mouse.isOnPlayfield = true;
         mouse.tileX = tempX;
         mouse.tileY = tempY;
      }
   }
}